#!/usr/bin/env python3
"""
订单API接口模块
提供订单相关的API调用功能
"""

import json
from typing import Dict, List, Optional, Any
from common.api_client import APIClient
from common.logger import get_logger


class OrderAPI:
    """订单API接口类"""
    
    def __init__(self, base_url: str, api_client: Optional[APIClient] = None):
        """
        初始化订单API
        
        Args:
            base_url: API基础URL
            api_client: API客户端实例，如果为None则创建新实例
        """
        self.base_url = base_url.rstrip('/')
        self.api_client = api_client or APIClient(base_url=self.base_url)
        self.logger = get_logger(__name__)
        
        # API端点
        self.endpoints = {
            'orders': '/api/orders',
            'order_detail': '/api/orders/{order_id}',
            'create_order': '/api/orders',
            'order_status': '/api/orders/{order_id}/status',
            'order_items': '/api/orders/{order_id}/items',
            'user_orders': '/api/users/{user_id}/orders',
            'cancel_order': '/api/orders/{order_id}/cancel',
            'payment': '/api/orders/{order_id}/payment',
            'shipping': '/api/orders/{order_id}/shipping'
        }
    
    def create_order(self, order_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建订单
        
        Args:
            order_data: 订单数据
                {
                    "user_id": 用户ID,
                    "items": [
                        {
                            "product_id": 商品ID,
                            "quantity": 数量,
                            "price": 单价
                        }
                    ],
                    "shipping_address": "收货地址",
                    "payment_method": "支付方式"
                }
        
        Returns:
            创建结果
        """
        self.logger.info(f"创建订单 - 用户ID: {order_data.get('user_id')}")
        
        try:
            response = self.api_client.post(
                self.endpoints['create_order'],
                data=order_data
            )
            
            if response.get('success'):
                order_id = response.get('data', {}).get('order_id')
                self.logger.info(f"订单创建成功: {order_id}")
            else:
                self.logger.warning(f"订单创建失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"创建订单异常: {str(e)}")
            return {
                'success': False,
                'message': f"创建订单失败: {str(e)}",
                'error': str(e)
            }
    
    def get_order_list(self, page: int = 1, limit: int = 10, filters: Optional[Dict] = None) -> Dict[str, Any]:
        """
        获取订单列表
        
        Args:
            page: 页码
            limit: 每页数量
            filters: 过滤条件
                {
                    "user_id": 用户ID,
                    "status": "订单状态",
                    "start_date": "开始日期",
                    "end_date": "结束日期"
                }
        
        Returns:
            订单列表数据
        """
        self.logger.info(f"获取订单列表 - 页码: {page}, 数量: {limit}")
        
        params = {
            'page': page,
            'limit': limit
        }
        
        if filters:
            params.update(filters)
        
        try:
            response = self.api_client.get(
                self.endpoints['orders'],
                params=params
            )
            
            if response.get('success'):
                self.logger.info(f"订单列表获取成功，共 {response.get('data', {}).get('total', 0)} 条记录")
            else:
                self.logger.warning(f"订单列表获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取订单列表异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取列表失败: {str(e)}",
                'error': str(e)
            }
    
    def get_order_detail(self, order_id: int) -> Dict[str, Any]:
        """
        获取订单详情
        
        Args:
            order_id: 订单ID
        
        Returns:
            订单详情数据
        """
        self.logger.info(f"获取订单详情: {order_id}")
        
        try:
            endpoint = self.endpoints['order_detail'].format(order_id=order_id)
            response = self.api_client.get(endpoint)
            
            if response.get('success'):
                self.logger.info(f"订单详情获取成功: {order_id}")
            else:
                self.logger.warning(f"订单详情获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取订单详情异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取详情失败: {str(e)}",
                'error': str(e)
            }
    
    def get_user_orders(self, user_id: int, page: int = 1, limit: int = 10) -> Dict[str, Any]:
        """
        获取用户订单列表
        
        Args:
            user_id: 用户ID
            page: 页码
            limit: 每页数量
        
        Returns:
            用户订单列表
        """
        self.logger.info(f"获取用户订单: {user_id}")
        
        try:
            endpoint = self.endpoints['user_orders'].format(user_id=user_id)
            response = self.api_client.get(endpoint, params={'page': page, 'limit': limit})
            
            if response.get('success'):
                self.logger.info(f"用户订单获取成功: {user_id}")
            else:
                self.logger.warning(f"用户订单获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取用户订单异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取用户订单失败: {str(e)}",
                'error': str(e)
            }
    
    def update_order_status(self, order_id: int, status: str, notes: Optional[str] = None) -> Dict[str, Any]:
        """
        更新订单状态
        
        Args:
            order_id: 订单ID
            status: 新状态
            notes: 状态变更说明
        
        Returns:
            更新结果
        """
        self.logger.info(f"更新订单状态: {order_id} -> {status}")
        
        update_data = {'status': status}
        if notes:
            update_data['notes'] = notes
        
        try:
            endpoint = self.endpoints['order_status'].format(order_id=order_id)
            response = self.api_client.put(endpoint, data=update_data)
            
            if response.get('success'):
                self.logger.info(f"订单状态更新成功: {order_id}")
            else:
                self.logger.warning(f"订单状态更新失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"更新订单状态异常: {str(e)}")
            return {
                'success': False,
                'message': f"更新状态失败: {str(e)}",
                'error': str(e)
            }
    
    def cancel_order(self, order_id: int, reason: Optional[str] = None) -> Dict[str, Any]:
        """
        取消订单
        
        Args:
            order_id: 订单ID
            reason: 取消原因
        
        Returns:
            取消结果
        """
        self.logger.info(f"取消订单: {order_id}")
        
        cancel_data = {}
        if reason:
            cancel_data['reason'] = reason
        
        try:
            endpoint = self.endpoints['cancel_order'].format(order_id=order_id)
            response = self.api_client.post(endpoint, data=cancel_data)
            
            if response.get('success'):
                self.logger.info(f"订单取消成功: {order_id}")
            else:
                self.logger.warning(f"订单取消失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"取消订单异常: {str(e)}")
            return {
                'success': False,
                'message': f"取消订单失败: {str(e)}",
                'error': str(e)
            }
    
    def process_payment(self, order_id: int, payment_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        处理订单支付
        
        Args:
            order_id: 订单ID
            payment_data: 支付数据
                {
                    "payment_method": "支付方式",
                    "amount": 支付金额,
                    "transaction_id": "交易ID"
                }
        
        Returns:
            支付结果
        """
        self.logger.info(f"处理订单支付: {order_id}")
        
        try:
            endpoint = self.endpoints['payment'].format(order_id=order_id)
            response = self.api_client.post(endpoint, data=payment_data)
            
            if response.get('success'):
                self.logger.info(f"订单支付成功: {order_id}")
            else:
                self.logger.warning(f"订单支付失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"处理订单支付异常: {str(e)}")
            return {
                'success': False,
                'message': f"支付失败: {str(e)}",
                'error': str(e)
            }
    
    def update_shipping_info(self, order_id: int, shipping_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        更新配送信息
        
        Args:
            order_id: 订单ID
            shipping_data: 配送数据
                {
                    "tracking_number": "物流单号",
                    "shipping_method": "配送方式",
                    "estimated_delivery": "预计送达时间"
                }
        
        Returns:
            更新结果
        """
        self.logger.info(f"更新配送信息: {order_id}")
        
        try:
            endpoint = self.endpoints['shipping'].format(order_id=order_id)
            response = self.api_client.put(endpoint, data=shipping_data)
            
            if response.get('success'):
                self.logger.info(f"配送信息更新成功: {order_id}")
            else:
                self.logger.warning(f"配送信息更新失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"更新配送信息异常: {str(e)}")
            return {
                'success': False,
                'message': f"更新配送信息失败: {str(e)}",
                'error': str(e)
            }
    
    def get_order_items(self, order_id: int) -> Dict[str, Any]:
        """
        获取订单商品项
        
        Args:
            order_id: 订单ID
        
        Returns:
            订单商品项列表
        """
        self.logger.info(f"获取订单商品项: {order_id}")
        
        try:
            endpoint = self.endpoints['order_items'].format(order_id=order_id)
            response = self.api_client.get(endpoint)
            
            if response.get('success'):
                items = response.get('data', [])
                self.logger.info(f"订单商品项获取成功: {order_id}, 共 {len(items)} 项")
            else:
                self.logger.warning(f"订单商品项获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取订单商品项异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取商品项失败: {str(e)}",
                'error': str(e)
            }
    
    def add_order_item(self, order_id: int, item_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        添加订单商品项
        
        Args:
            order_id: 订单ID
            item_data: 商品项数据
                {
                    "product_id": 商品ID,
                    "quantity": 数量,
                    "price": 单价
                }
        
        Returns:
            添加结果
        """
        self.logger.info(f"添加订单商品项: {order_id}")
        
        try:
            endpoint = self.endpoints['order_items'].format(order_id=order_id)
            response = self.api_client.post(endpoint, data=item_data)
            
            if response.get('success'):
                self.logger.info(f"订单商品项添加成功: {order_id}")
            else:
                self.logger.warning(f"订单商品项添加失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"添加订单商品项异常: {str(e)}")
            return {
                'success': False,
                'message': f"添加商品项失败: {str(e)}",
                'error': str(e)
            }
    
    def remove_order_item(self, order_id: int, item_id: int) -> Dict[str, Any]:
        """
        移除订单商品项
        
        Args:
            order_id: 订单ID
            item_id: 商品项ID
        
        Returns:
            移除结果
        """
        self.logger.info(f"移除订单商品项: {order_id} - {item_id}")
        
        try:
            endpoint = f"{self.endpoints['order_items'].format(order_id=order_id)}/{item_id}"
            response = self.api_client.delete(endpoint)
            
            if response.get('success'):
                self.logger.info(f"订单商品项移除成功: {order_id} - {item_id}")
            else:
                self.logger.warning(f"订单商品项移除失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"移除订单商品项异常: {str(e)}")
            return {
                'success': False,
                'message': f"移除商品项失败: {str(e)}",
                'error': str(e)
            }


# 使用示例
if __name__ == "__main__":
    # 创建订单API实例
    order_api = OrderAPI("http://localhost:8000")
    
    # 测试创建订单
    test_order = {
        "user_id": 1,
        "items": [
            {
                "product_id": 1,
                "quantity": 2,
                "price": 99.99
            }
        ],
        "shipping_address": "测试地址 123号",
        "payment_method": "credit_card"
    }
    
    result = order_api.create_order(test_order)
    print("创建订单:", result)
    
    # 测试获取订单列表
    result = order_api.get_order_list(page=1, limit=5)
    print("订单列表:", result)
    
    # 测试获取订单详情
    if result.get('success') and result.get('data', {}).get('orders'):
        order_id = result['data']['orders'][0]['id']
        result = order_api.get_order_detail(order_id)
        print("订单详情:", result)
    
    # 测试更新订单状态
    result = order_api.update_order_status(order_id, "processing")
    print("更新状态:", result)